import csv
from random import randint, random

from django.core.management.base import BaseCommand

from app.models import Goods


class Command(BaseCommand):
    help = '更新数据库中的商品信息'

    def handle(self, *args, **options):
        Goods.objects.all().delete()

        goods_list = []
        with open('data.csv', 'r', encoding='utf-8') as f:
            csv_reader = csv.reader(f)
            header = next(csv_reader)  # 跳过表头
            for row in csv_reader:
                name = row[0]
                try:
                    price = float(row[1])
                except:
                    price = randint(0, 10000) + random()
                storage = randint(0, 1000000)

                goods_list.append(Goods(name=name, price=price, storage=storage))

        Goods.objects.bulk_create(goods_list)
        self.stdout.write(self.style.SUCCESS('所有商品信息已成功更新到数据库。'))
